<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>评论表</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div>
  <h2>评论列表</h2>
  <ul id="comments-list">
  </ul>
  <form id="add-comm-form" action="" method="post">
    <label>
      输入评论：
      <input id="comm-input" type="text" placeholder="请输入评论...">
    </label>
    <button>发表</button>
  </form>
</div>
<script>
  $(function () {
    function getComments() {
      $.ajax({
        url: 'http://localhost:8080/getComments',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
          console.log("获取了评论数据：", data);
          let comm = data.data;
          let tableData = "<tr>\n"+
                  "<th>comm_id</th>"+
                  "<th>user_id</th>"+
                  "<th>book_id</th>"+
                  "<th>comm</th>"+
                  "<th>comm_like</th>";
          for (let i = 0;i<comm.lengh;i++)


          updateComments(data);
        },
        complete: function () { // Ajax请求结束后继续轮询
          setTimeout(getComments, 10000);
        }
      });
    }

    function addComment() {
      var comm = $('#comm-input').val();
      $.ajax({
        url: '/addComment',
        type: 'POST',
        dataType: 'json',
        data: {
          content: comm
        },
        success: function (data) {
          $('#comm-input').val('');
          console.log("添加了新评论：", data);
          updateComments([data]);
        }
      });
    }

    function updateComments(data) {
      var commentsHtml = '';
      for (var i = 0; i < data.length; i++) {
        commentsHtml += '<li>' + data[i].content + '</li>';
      }
      $('#comments-list').html(commentsHtml);
    }

    // 页面加载时获取评论
    getComments();

    // 监听表单提交事件
    $('#add-comm-form').submit(function (event) {
      event.preventDefault();
      addComment();
    });
  });
</script>
</body>
</html>